<template>
  <el-card shadow="hover" style="width: 350px">
    <template #header>
      <div class="option-header">
        <div class="option-header-content"><span>双鲨期权</span></div>
        <div v-if="props.calcSuccess=='true'" class="option-header-content"><span style="color: #22bb98 ">计算成功</span></div>
        <!--        <div v-if="props.calcSuccess=='false'" class="option-header-content"><span style="color: #e53c3c">计算失败</span></div>-->
        <div v-if="props.calcSuccess=='false'" class="option-header-content">
          <el-tooltip  effect="light"  >
            <template #content> <div style="width: 280px;">
              <span style="color: #e53c3c;">{{props.errorMsg}}</span>
            </div> </template>
            <span style="color: #e53c3c">计算失败</span>
          </el-tooltip>
        </div>
        <div>
          <el-button style="background: transparent;" :disabled="cpoyWait" class="delete" @click="copy" title="复制">
            <el-icon>
              <copy-document/>
            </el-icon>
          </el-button>
          <el-button style="background: transparent;" class="delete" @click="cancel" title="关闭">
            <el-icon>
              <circle-close/>
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>

    <el-form ref="formRef" :disabled="form.data.readOnly" :model="form.data" label-width="auto" size="small"
             :rules="rules">
      <div class="optionst01">
        <el-form-item label="观察方式">
          <el-radio-group v-model="form.data.exerciseType" size="small" :fill="getColor()">
            <el-radio label="European">欧式观察</el-radio>
            <el-radio label="American">美式观察</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="交易方向" prop="payDirection">
          <el-radio-group v-model="form.data.payDirection" size="small" :fill="getColor()">
            <el-radio-button label="1">买入</el-radio-button>
            <el-radio-button label="-1">卖出</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标的" label-width="auto" prop="instrumentId">
          <Underlyer v-model="form.data.instrumentId" @change="onBlurInstrumentId" :underlyerId="form.data.instrumentId" :filterDate="true" ref="underlyerIdRef"/>
        </el-form-item>
        <!--合约乘数-->
        <!--      todo-->
        <!--涨跌类型-->
        <el-form-item label="涨跌类型" label-width="auto" prop="optionType">
          <el-radio-group v-model="form.data.optionType" size="small">
            <el-radio label="Call">看涨</el-radio>
            <el-radio label="Put">看跌</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="起始日" label-width="auto" prop="effectiveDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.effectiveDate" @blur="onBlurTerminationDate" type="date" placeholder="">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="期限" label-width="auto" prop="term">
          <Numberinput v-model="form.data.term" append="D"/>
        </el-form-item>

        <el-form-item :label="form.data.exerciseType === 'European'?'观察日':'到期日'" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationDate" type="date" placeholder=""/>
        </el-form-item>

        <el-form-item label="到期支付偏移" label-width="auto" prop="paymentDaysOffset">
          <Numberinput v-model="form.data.paymentDaysOffset" append="D"/>

        </el-form-item>

        <el-form-item label="到期支付日" label-width="auto" prop="terminationDate">
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.terminationPaymentDate"
                          type="date"
                          placeholder=""/>
        </el-form-item>

        <el-form-item v-if="startRequired" label="行权开始日" label-width="auto"
                      prop="startDate">
          <!--          <el-col :span="8">-->
          <!--            <el-checkbox-group v-model="form.data.isIncludeStartDate" size="small">-->
          <!--              <el-checkbox label="包含" name="type">包含</el-checkbox>-->
          <!--            </el-checkbox-group>-->
          <!--          </el-col>-->
          <!--          <el-col :span="16">-->
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.startDate" type="date" placeholder="">
          </el-date-picker>
          <!--          </el-col>-->
        </el-form-item>

        <el-form-item v-if="endRequired" label="行权结束日" label-width="auto" prop="endDate">

          <!--          <el-col :span="8">-->
          <!--            <el-checkbox-group v-model="form.data.isIncludeEndDate" size="small">-->
          <!--              <el-checkbox label="包含" name="type">包含</el-checkbox>-->
          <!--            </el-checkbox-group>-->
          <!--          </el-col>-->
          <!--          <el-col :span="16">-->
          <el-date-picker value-format="YYYY-MM-DD" v-model="form.data.endDate" type="date" placeholder="">
          </el-date-picker>
          <!--          </el-col>-->
        </el-form-item>

        <el-form-item label="名义本金" prop="notional">
          <InputAmount v-model:value="form.data.notional" append="元" precision="2"></InputAmount>
        </el-form-item>


        <el-form-item label="期初价格" label-width="auto">
          <el-col :span="8">
            <el-checkbox name="status" false-label="0" true-label="1" v-model="form.data.priceOnWait">待定</el-checkbox>
          </el-col>
          <el-col :span="16">
            <InputAmount v-model:value="form.data.spotPrice" :disabled="form.data.priceOnWait=='1'"
                         precision="2" append="元"/>
          </el-col>
        </el-form-item>

        <el-form-item label="交易数量" prop="optionEntitlement">
          <Numberinput v-model="form.data.optionEntitlement" precision="2"  :disabled="form.data.priceOnWait=='1'" @change="optionEntitlementChange"/>
        </el-form-item>
        <el-form-item label="参与率" prop="participationRate">
          <Numberinput v-model="form.data.participationRate" precision="2" append="%"/>
        </el-form-item>
      </div>
      <!---------------------------------------------- 分割线---------------------------------------------------------->
      <div class="optionst02">
        <el-form-item label="行权价比例" prop='strikePercentage'>
          <el-col :span="8">
            <el-checkbox label="1" v-model="form.data.moneynessOption" name="type">年化</el-checkbox>
          </el-col>
          <el-col :span="16">
            <Numberinput v-model="form.data.strikePercentage" @blur="linkPercentage(form,form.data.strikePercentage,form.data.spotPrice,'data.strike')" append="%"/>
          </el-col>
        </el-form-item>
        <el-form-item label="行权价" prop='strike'>
          <Numberinput v-model="form.data.strike" precision="4" @blur="linkPrice(form,form.data.strike,form.data.spotPrice,'data.strikePercentage')"/>
        </el-form-item>

        <el-form-item label="敲出方向" prop='knockType'>
          <dictCombox v-model="form.data.knockType"
                      dictType="touchknockType" disabled></dictCombox>
        </el-form-item>

        <el-form-item label="观察频率" prop='scheduleType'>
          <dictCombox v-model="form.data.scheduleType"
                      dictType="scheduleType" disabled></dictCombox>
        </el-form-item>
        <el-form-item label="障碍价比例" prop='triggerRate'>
          <Numberinput v-model="form.data.triggerRate" @input="onTriggerRateChange" append="%"/>
        </el-form-item>
        <el-form-item label="障碍价" v-if="false" prop='triggerPrice'>
          <Numberinput v-model="form.data.triggerPrice" @input="onTriggerPriceChange"/>
        </el-form-item>
        <el-form-item label="敲出补偿比例" prop='rebateRate'>
          <el-col :span="8">
            <el-checkbox v-model="form.data.moneynessOption2" name="status" false-label="0" true-label="1">年化
            </el-checkbox>
          </el-col>
          <el-col :span="16">
            <Numberinput v-model="form.data.rebateRate" @input="onRebateRateChange" append="%"/>
          </el-col>
        </el-form-item>
        <el-form-item label="敲出补偿价" v-if="false" prop='rebatePrice'>
          <Numberinput v-model="form.data.rebatePrice" @input="onRebatePriceChange"/>
        </el-form-item>
        <el-form-item label="保底收益率" prop='minYieldRate'>
          <el-col :span="8">
            <el-checkbox name="status" false-label="0" true-label="1" v-model="form.data.moneynessOption3">年化
            </el-checkbox>
          </el-col>
          <el-col :span="16">
            <Numberinput v-model="form.data.minYieldRate" @input="onMinYieldRateChange" append="%"/>
          </el-col>
        </el-form-item>
        <el-form-item label="保底收益" v-if="false" prop='minYieldPrice'>
          <Numberinput v-model="form.data.minYieldPrice" @input="onMinYieldPriceChange"/>
        </el-form-item>


        <!--        <el-form-item label="是否年化">-->
        <!--          <dictCombox v-model="form.data.moneynessOption"-->
        <!--                      dictType="boolType"-->
        <!--                      :style="{width: '100%'}"></dictCombox>-->
        <!--        </el-form-item>-->
        <el-form-item label="计息天数" v-if="false"
                      v-show="form.data.moneynessOption =='1'||form.data.moneynessOption2 =='1'||form.data.moneynessOption3 =='1'"
                      prop="daycounterTerm">
          <Numberinput v-model="form.data.term" append="D"/>
        </el-form-item>

        <el-form-item label="计息基准"
                      v-show="form.data.moneynessOption =='1'||form.data.moneynessOption2 =='1'||form.data.moneynessOption3 =='1'"
                      prop="daycounter">
          <dictCombox v-model="form.data.daycounter" prop='disDayCount'
                      dictType="dayCounter"
                      :style="{width: '100%'}"></dictCombox>
        </el-form-item>

        <el-form-item class="operation">
          <el-button type="primary" @click="calc">计算</el-button>
          <el-button @click="save2CalcLog" v-show="props.useType=='calc'" :disabled="form.data.priceOnWait=='1'">存为草稿</el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="optionst03">
      <PricingParam ref="PricingParamRef" :formData="form.data"  :valueDate="props.valueDate"  size="small" label-width="auto" :productType="productType"
                    :disabled="form.data.readOnly" :index="props.index"
                    :calcPricingParam="props.calcPricingParam"></PricingParam>
    </div>
    <singleResult :result="form.result" :index="props.index"></singleResult>
  </el-card>
</template>

<script setup>
import {linkPercentage,linkPrice}  from '@/views/calc/otcOtion/instrument/common/formula'
import {getCurrentInstance, onMounted, onUpdated, provide, reactive, ref, toRefs, watch, nextTick} from 'vue'
import Underlyer from '../../../../xquant/base/underlyer'
import Numberinput from '../../../../xquant/base/number'
import InputAmount from '../../../../xquant/base/InputAmount'
import dictCombox from '@/xquant/base/dictCombox'
import PricingParam from '@/views/calc/otcOtion/pricingparam/index'
import singleResult from '@/views/calc/otcOtion/result/single'
import {getTradeDay} from '@/utils/calc'
import {isVoid, isNotVoid} from '@/utils/util'
import {getTerminationPaymentDate} from '@/api/calc/otcOption/calc'
import {formartFormP4, formartTableP2, unFormartNumber, formartFormP2, numberPrecision} from '@/utils/numberUtil'
import * as Util from '../../../../utils/util'
import {setCommonSpotPrice} from '@/views/calc/otcOtion/instrument/common/common'
import {validateDates} from "./common/validate";
const getColor = () => {
  return form.data.payDirection == '1' ? '#E53C3C' : '#22BB98'
}
 const {proxy} = getCurrentInstance()

const productType = 'doubleShark'
const startRequired = ref(false)
const endRequired = ref(false)
const labelWidth = ref('111px')
const cpoyWait = ref(false)
const form = reactive({
  data: {
    payDirection: '1',
    instrumentId: null,
    optionType: 'Call',
    effectiveDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    terminationDate: '',
    terminationPaymentDate: '',
    term: 30,
    paymentDaysOffset: '0',
    priceOnWait: '0',
    spotPrice: '',
    strikePercentage: '100',
    triggerRate: '',
    triggerPrice: '',
    rebateRate: '',
    rebatePrice: '',
    minYieldRate: '',
    minYieldPrice: '',
    strike: 0,
    notional: '',
    scheduleType: '',
    knockType: '',
    optionEntitlement: '',
    moneynessOption: '1',
    moneynessOption2: '0',
    moneynessOption3: '0',
    daycounter: 'Actual/365',
    participationRate: 100,
    calendar: 'CHINA_EX',
    daycounterTerm: '365',
    exerciseType: 'European',
    isIncludeEndDate: '',
    endDate: '',
    isIncludeStartDate: '',
    startDate: '',
  },
  result: {},
  initFlag : ''
})
const rules = {
  payDirection: [{required: true, message: '请选择交易方向', trigger: 'change'}],
  instrumentId: [{required: true, message: ' ', trigger: 'change'}],
  optionType: [{required: true, message: '请选择涨跌类型', trigger: 'change'}],
  effectiveDate: [{required: true, message: ' ', trigger: 'change'}],
  terminationDate: [{required: true, message: ' ', trigger: 'change'}],
  term: [{required: true, message: ' ', trigger: 'change'}],
  paymentDaysOffset: [{required: true, message: ' ', trigger: 'change'}],
  notional: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  daycounter: [{required: true, message: ' ', trigger: 'change'}],
  daycounterTerm: [{required: true, message: ' ', trigger: 'change'}],
  spotPrice: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  optionEntitlement: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      if (form.data.priceOnWait == '1') {
        return true
      }
      return Number(value) > 0
    }, message: ' ', trigger: 'change'
  }],
  strike: [{required: true, message: ' ', trigger: 'blur'}],
  strikePercentage: [{required: true, message: ' ', trigger: 'change'}],
  triggerRate: [{required: true, message: ' ', trigger: 'change'}],
  triggerPrice: [{required: true, message: ' ', trigger: 'change'}],
  rebateRate: [{required: true, message: ' ', trigger: 'change'}],
  rebatePrice: [{required: true, message: ' ', trigger: 'change'}],
  participationRate: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmountPecentage: [{required: true, message: ' ', trigger: 'change'}],
  paymentAmount: [{required: true, message: ' ', trigger: 'change'}],
  minYieldRate: [{required: true, message: ' ', trigger: 'change'}],
  minYieldPrice: [{required: true, message: ' ', trigger: 'change'}],
  startDate: [{required: startRequired, message: ' ', trigger: 'change'}],
  endDate: [{required: endRequired, message: ' ', trigger: 'change'}]

}

watch(() => props.result, (nv, ov) => {
  let other = {
    'type': '双鲨',
    '标的': computed(() => {
      if (proxy.$refs.underlyerIdRef&&proxy.$refs.underlyerIdRef.underlyerIdsList[0]) {
        return (proxy.$refs.underlyerIdRef.underlyerIdsList[0].productName+'').trim().split(' ').join(',')
      }
    }),
    '交易日期': props.valueDate,
    '观察方式': form.data.exerciseType == 'European' ? '欧式观察' : '美式观察',
    '合约类型': form.data.optionType == 'Call' ? 'C' : 'P',
    '合约交易方向': form.data.payDirection == '1' ? '客户卖价' :  '客户买价',
    '到期日': form.data.terminationDate,
    '执行价': formartFormP2(form.data.strike),
    '数量': formartFormP2(form.data.optionEntitlement),
    '名义金额': formartFormP2(form.data.notional),
    '开仓标的价': formartFormP2(form.data.spotPrice),
    '期权单价': computed(() => {
      if (nv) {
        return formartFormP2(nv.npv / form.data.optionEntitlement)
      }
    }),
    '百分比估值': computed(() => {
      if (nv) {
        return formartFormP2(100 * nv.npv / form.data.notional)
      }
    }),
  }
  form.result = Object.assign(other, nv)
}, {immediate: true})
watch(() => form.data.priceOnWait, (nv, ov) => {
  if (nv == '1') {
    form.data.spotPrice = 0
  } else {
    setSpotPrice()
  }
})
watch(() => form.data.optionType, (nv, ov) => {
  if (nv == 'Call') {
    form.data.knockType = 'up'
  } else {
    form.data.knockType = 'down'
  }
}, {
  immediate: true
})


const onBlurTerminationDate= (nv, ov) => {
  let a = proxy.$moment(form.data.terminationDate)
  let b = proxy.$moment(form.data.terminationPaymentDate)
  form.data.paymentDaysOffset = b.diff(a, 'days')
}
watch(() => [form.data.terminationDate], ([nv], [ov]) => {
  if (nv == null) return
  let a = proxy.$moment(form.data.terminationDate)
  let b = proxy.$moment(form.data.terminationPaymentDate)
  // form.data.paymentDaysOffset = b.diff(a, 'days')
  form.data.terminationPaymentDate = a.add(form.data.paymentDaysOffset, 'days').format('YYYY-MM-DD')
  getTerminationPaymentDate({
    'calDay': form.data.terminationPaymentDate
  }).then(response => {
    if (response.errorCode == 0 && response.result != null) {
      form.data.terminationPaymentDate = response.result.CAL_DAY
    } else {

    }
  })
})
watch(() => [form.data.terminationPaymentDate], ([nv], [ov]) => {
  if (nv == null) return
  let b = proxy.$moment(form.data.terminationPaymentDate)
  let a = proxy.$moment(form.data.terminationDate)
  if (b.diff(a) < 0) {
    form.data.terminationPaymentDate = form.data.terminationDate
  }
})
watch(() => [form.data.effectiveDate, form.data.terminationDate], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {
    let a = proxy.$moment(n2v)
    let b = proxy.$moment(nv)
    form.data.term = a.diff(b, 'days')
  }
})
watch(() => [form.data.term], ([newValue], [oldValue]) => {
  if (isNotVoid(String(form.data.effectiveDate)) && isNotVoid(String(newValue))) {
    let a = proxy.$moment(form.data.effectiveDate)
    form.data.terminationDate = a.add(newValue, 'days').format('YYYY-MM-DD')
    onpaymentDaysOffsetChange()
  }
})
watch(() => [form.data.notional, form.data.spotPrice], ([nv, n2v], [ov, o2v]) => {
  if (!proxy.lsh.isEmpty(nv) && !proxy.lsh.isEmpty(n2v)) {

    form.data.optionEntitlement = String(Number(nv) / Number(n2v))
  }
})


watch(() => [form.data.notional], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(newValue, form.data.spotPrice, form.data.optionEntitlement)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.optionEntitlement = proxy.lsh.divide(newValue, form.data.spotPrice).toFixed(4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.spotPrice = proxy.lsh.divide(newValue, form.data.optionEntitlement).toFixed(4)
      return
    }
  }
})
watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  if (optionEntitlementLinkValid(form.data.notional, newValue, form.data.optionEntitlement)) {
    return
  }

  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.notional))) {
      form.data.optionEntitlement = proxy.lsh.divide(form.data.notional, newValue).toFixed(4)
      return
    }
    if (isNotVoid(String(form.data.optionEntitlement))) {
      form.data.notional = proxy.lsh.multiply(form.data.optionEntitlement, newValue).toFixed(4)
      return
    }
  }
})
const optionEntitlementChange = (newValue) => {
  if (form.data.priceOnWait == '1') return
  if (optionEntitlementLinkValid(form.data.notional, form.data.spotPrice, newValue)) {
    return
  }
  if (isNotVoid(String(newValue))) {
    if (isNotVoid(String(form.data.spotPrice))) {
      form.data.notional = proxy.lsh.multiply(newValue, form.data.spotPrice).toFixed(0)
      return
    }
    if (isNotVoid(String(form.data.notional))) {
      form.data.spotPrice = proxy.lsh.divide(form.data.notional, newValue).toFixed(4)
      return
    }
  }
}


watch(() => [form.data.notional], ([newValue], [oldValue]) => {
  if (isNotVoid(String(newValue))) {
    //敲出补偿
    if (!rebateRateLinkValid(newValue, form.data.rebateRate, form.data.rebatePrice)) {
      if (isNotVoid(String(form.data.rebateRate))) {
        form.data.rebatePrice = proxy.lsh.round(proxy.lsh.multiply(newValue, proxy.lsh.divide(form.data.rebateRate, 100)), 4)
      } else if (isNotVoid(String(form.data.strike))) {
        form.data.rebateRate = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(form.data.rebatePrice, newValue), 100), 4)
      }
    }
    //保底收益率
    if (!minYieldLinkValid(newValue, form.data.minYieldRate, form.data.minYieldPrice)) {
      if (isNotVoid(String(form.data.minYieldRate))) {
        form.data.minYieldPrice = proxy.lsh.round(proxy.lsh.multiply(newValue, proxy.lsh.divide(form.data.minYieldRate, 100)), 4)
      } else if (isNotVoid(String(form.data.strike))) {
        form.data.minYieldRate = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(form.data.minYieldPrice, newValue), 100), 4)
      }
    }
  }
})


watch(() => [form.data.spotPrice], ([newValue], [oldValue]) => {
  linkPercentage(form,form.data.strikePercentage,form.data.spotPrice,'data.strike')
})

const onStrikeChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.spotPrice))) {
    form.data.strikePercentage = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(a, form.data.spotPrice), 100), 4)
    return
  }
}

const onStrikePercentageChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.spotPrice))) {
    form.data.strike = proxy.lsh.multiply(proxy.lsh.divide(newValue, 100), form.data.spotPrice).toFixed(4)
    return
  }
 proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():'';
}


const onTriggerPriceChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.spotPrice))) {
    form.data.triggerRate = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(a, form.data.spotPrice), 100), 2)
    return
  }
}

const onTriggerRateChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.spotPrice))) {
    form.data.triggerPrice = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(newValue, 100), form.data.spotPrice), 4)
    return
  }
}


const onRebatePriceChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.spotPrice))) {
    form.data.rebateRate = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(a, form.data.notional), 100), 2)
    return
  }
}

const onRebateRateChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.notional))) {
    form.data.rebatePrice = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(newValue, 100), form.data.notional), 4)
    return
  }
}

const onMinYieldPriceChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.notional))) {
    form.data.minYieldRate = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(a, form.data.notional), 100), 2)
    return
  }
}

const onMinYieldRateChange = (newValue) => {
  let a = newValue
  if (isNotVoid(String(form.data.notional))) {
    form.data.minYieldPrice = proxy.lsh.round(proxy.lsh.multiply(proxy.lsh.divide(newValue, 100), form.data.notional), 4)
    return
  }
}






//敲出补偿
function rebateRateLinkValid(notional, rebateRate, rebatePrice) {
  if (isNotVoid(String(notional)) && isNotVoid(String(rebateRate)) && isNotVoid(String(rebatePrice))) {
    if (proxy.lsh.isEqual(rebatePrice, proxy.lsh.multiply(proxy.lsh.divide(rebateRate, 100), notional).toFixed(4))) {
      return true
    } else {
      return false
    }
  }
}

//保底收益率
function minYieldLinkValid(notional, minYieldRate, minYieldPrice) {
  if (isNotVoid(String(notional)) && isNotVoid(String(minYieldRate)) && isNotVoid(String(minYieldPrice))) {
    if (proxy.lsh.isEqual(minYieldPrice, proxy.lsh.multiply(proxy.lsh.divide(minYieldRate, 100), notional).toFixed(4))) {
      return true
    } else {
      return false
    }
  }
}

function optionEntitlementLinkValid(notional, spotPrice, optionEntitlement) {
  if (isNotVoid(String(notional)) && isNotVoid((String(spotPrice))) && isNotVoid(String(optionEntitlement))) {
    if (proxy.lsh.isEqual(optionEntitlement, proxy.lsh.divide(notional, spotPrice).toFixed(4))) {
      return true
    } else {
      return false
    }
  }
}

watch(() => [props.cfgId,form.data.instrumentId], ([newId, oldId]) => {
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
})

const onBlurInstrumentId = () => {
  setSpotPrice()
  getPricingCfg()
  setTimeout(() => {
    proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }, 1000);
}
watch(() => props.valueDate, (newValue, oldValue) => {
  if (newValue != oldValue) {
    setSpotPrice()
    //触发修改定价参数的价格
    proxy.$refs.PricingParamRef.setSpotPrice({
      valueDate:props.valueDate,
      instrumentId:form.data.instrumentId
    })
   proxy.$refs.PricingParamRef?proxy.$refs.PricingParamRef.calcRateByCode():''
  }
})

watch(() => form.data.exerciseType, (nv, ov) => {
  if (form.data.exerciseType == 'American') {
    startRequired.value = true
    endRequired.value = true
    form.data.startDate = form.data.effectiveDate
    form.data.endDate = form.data.terminationDate
    form.data.scheduleType = '1'
  } else {
    startRequired.value = false
    endRequired.value = false
    form.data.scheduleType = '2'
  }
}, {
  immediate: true
})

const props = defineProps({
  /*是否为重放*/
  isReCalc: {
    type: Boolean,
    default: false
  },
  calcSuccess:{
    type: String,
    default: ''
  },
  errorMsg:{
    type: String,
    default: ''
  },
  save2CalcLog: {type: Function, default: null},
  index: {
    type: String,
    default: ''
  },
  del: {
    type: Function,
    default: null
  },
  copy: {
    type: Function,
    default: null
  },
  calc: {
    type: Function,
    default: null
  },
  getDefaultCfg: {
    type: Function,
    default: null
  },
  calcPricingParam: {
    type: Object,
    default: {}
  },
  result: {
    type: Object,
    default: {}
  },
  setformData: {
    type: Function,
    default: null
  },
  formData: {
    type: Object,
    default: null
  },
  cfgId: {type: String, default: ''},
  valueDate: {type: String, default: ''}
})
const getResult = () => {
  var data = []
  for (var item in props.result) {
    if (['npv', 'delta', 'gamma', 'vega', 'theta', 'rho', 'spotPrice', 'dscRate'].includes(item)) {
      data.push({
        key: item,
        val: proxy.lsh.ceil(props.result[item], 4)
      })
    }
  }
  return data
}
//定价参数
const getPricingCfg = async () => {
  let query = {
    'calcPricingParam': {
      'cfgId': props.cfgId
    },
    'instrument': {
      'productType': 'doubleShark',
      'termsheet': {
        'underlyerIds': [form.data.instrumentId],
        'customLegs': [{
          'legId': 'leg01',
          'productType': 'doubleShark'
        }
        ],
        'legs': [{
          'legId': 'leg01',
          'payDirection': '1'
        }
        ]
      }
    }
  }
  //设置定价参数中的定盘价
  proxy.$refs.PricingParamRef.setSpotPrice({
    valueDate:props.valueDate,
    instrumentId:form.data.instrumentId
  })
  if (props.getDefaultCfg != null) {
    props.getDefaultCfg(query, props.index)
  }
}
const cancel = () => {
  props.del(props.index)
}
const copy = () => {
  props.copy(props.index)
  cpoyWait.value = true;
  setTimeout(() => {
    cpoyWait.value = false;
  }, 1000);
}
const calc = (flag) => {
  /*flag 标识 为All时单次计算不会提示成功或失败*/
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      validateDates(form)
      if (form.data.exerciseType == 'American') {
        if (form.data.minYieldRate > 0) {
          if (Number(form.data.minYieldRate) >= Number(form.data.rebateRate)) {
            proxy.$modal.alertWarning('保底收益不能大于补偿收益,请核对!')
            return
          }
          // form.data.rebateRate = form.data.rebateRate - form.data.minYieldRate;
        }
      }
      if (form.data.optionType == 'Call' && Number(form.data.triggerRate) <= Number(form.data.strikePercentage)) {
        proxy.$modal.alertWarning('障碍价必须大于行权价,请核对!')
        return
      }
      if (form.data.optionType == 'Put' && Number(form.data.triggerRate) >= Number(form.data.strikePercentage)) {
        proxy.$modal.alertWarning('障碍价必须小于行权价,请核对!')
        return
      }
      //欧式 障碍价比例加保底收益率必须大于行权价比例加敲出补偿比例
      if (form.data.exerciseType !== 'American' && proxy.lsh.add(Number(form.data.triggerRate), Number(form.data.minYieldRate)) <= proxy.lsh.add(Number(form.data.rebateRate), Number(form.data.strikePercentage))) {
        proxy.$modal.alertWarning('障碍价比例+保底收益率必须大于行权价比例+敲出补偿比例,请核对!')
        return
      }
      let calcPriceParam = getCalcPriceParam()
      //界面数值不变 直接在后台传入的参数中处理敲出和保底的年化
      let tempRebateRate = proxy.lsh.divide(form.data.rebateRate, 100).toFixed(2)
      let tempRebatePrice = form.data.rebatePrice
      if (form.data.moneynessOption2 == '1') {
        let annualized = Util.calcAnnualizedByTerminationPaymentDate(form.data)
        tempRebatePrice = form.data.notional * (tempRebateRate / 1) * annualized
        tempRebateRate = annualized * (form.data.rebatePrice / form.data.notional)
      }
      let tempMinYieldRate = proxy.lsh.divide(form.data.minYieldRate, 100).toFixed(2)
      let tempMinYieldPrice = form.data.minYieldPrice
      if (form.data.moneynessOption2 == '1') {
        let annualized = Util.calcAnnualizedByTerminationPaymentDate(form.data)
        tempMinYieldPrice = form.data.notional * (tempMinYieldRate / 1) * annualized
        tempMinYieldRate = annualized * (form.data.minYieldPrice / form.data.notional)
      }
      let otcOption = {
        instrument: {
          'termsheet': {
            'notional': form.data.notional,
            'notionalCurrency': 'CNY',
            'settlementType': 'C',
            'settlementCurrency': 'CNY',
            'effectiveDate': form.data.effectiveDate,
            'effectiveDateConv': 'Following',
            'terminationDate': form.data.terminationDate,
            'terminationDateConv': 'Following',
            'terminationDateCalendar': form.data.calendar,
            'underlyerIds': [
              form.data.instrumentId
            ],
            'calendars': [
              form.data.calendar
            ],
            'legs': [
              {
                'legId': 'leg01',
                'payDirection': form.data.payDirection
              }
            ],
            'customLegs': [
              {
                'payDirection': form.data.payDirection,
                periodOfAccrualInterestAdjust: '0',
                'participationRate': String(form.data.participationRate / 100),
                'productType': 'doubleShark',
                // 'optionType': form.data.optionType,
                'strikePercentage': proxy.lsh.divide(form.data.strikePercentage, 100).toFixed(2),
                'strike': form.data.strike,
                'exercise': {
                  'type': form.data.exerciseType,
                  'dates': form.data.exerciseType == 'American' ? [form.data.startDate, form.data.endDate] : [form.data.terminationDate],
                  'conv': 'Following',
                  'calendar': form.data.calendar
                },
                'paymentDateCalendar': form.data.calendar,
                'underlyers': [
                  {
                    'instrumentId': form.data.instrumentId,
                    'quoteType': '',
                    'spotPrice': form.data.spotPrice,
                    'basketWeight': '1',
                    'fixingDate': '',
                    'fixingDateConv': 'Preceding',
                    'fixingDateCalendar': form.data.calendar
                  }
                ],
                'numberOfOptions': '1',
                'optionEntitlement': form.data.optionEntitlement,
                'moneynessOption': form.data.moneynessOption,
                // 'daycounter':form.data.moneynessOption=='1'?form.data.daycounter:'',
                'fixingRounding': '-1',
                'settlementDateConv': 'Following',
                'settlementDateCalendar': form.data.calendar,
                'settlementDateOffset': form.data.paymentDaysOffset + 'D',
                'legId': 'leg01',
                'OptionTrade': {
                  'Premium': [
                    {
                      'PaymentDate': '',
                      'PaymentAmountRate': ''
                    }
                  ],
                  'OptionLegs': [
                    {
                      'ProductType': 'doubleShark',
                      'LegData': {
                        'TrdType': '1010',
                        'UnderlyerId': form.data.instrumentId,
                        'EffectiveDate': form.data.effectiveDate,
                        'TerminationDate': form.data.terminationDate,
                        'SettlementDateOffset': form.data.paymentDaysOffset,
                        'FixingDate': form.data.terminationDate,
                        'Notional': form.data.notional,
                        'Term': form.data.term,
                        'SpotPrice': form.data.spotPrice,
                        'Daycounter': form.data.daycounter,
                        'ObserveType': form.data.exerciseType == 'American' ? 'A' : 'E',
                        'OptionType': form.data.optionType,
                        'StrikeRate': proxy.lsh.round(proxy.lsh.divide(form.data.strikePercentage, 100), 2),
                        'TriggerRate': proxy.lsh.round(proxy.lsh.divide(form.data.triggerRate, 100), 2),
                        'TriggerLevelInclude': '1',
                        'RebateRate': tempRebateRate,
                        'RebatePrice': tempRebatePrice,
                        'PayStyle': null,
                        'ScheduleType': form.data.exerciseType == 'American' ? '1' : '',
                        'IfAnnual': form.data.moneynessOption,
                        'MinYield': tempMinYieldRate,
                        'MinYieldPrice': tempMinYieldPrice,
                        'ParticipationRate': form.data.participationRate / 100,
                        'RebateParticipationRate': form.data.participationRate / 100
                      }
                    }
                  ]
                }
              }
            ],
            'term': form.data.term,
            'rival': '',
            'memo': ''
          },
          'productType': 'doubleShark'
        },
        calcPricingParam: {
          valueDate: props.valueDate,
          cfgId: props.cfgId,
          calcPPCode: calcPriceParam.calcPPCode,
          underlyingPricingParams: [
            {
              underlyingID: form.data.instrumentId,
              dividend: calcPriceParam.dividend,
              volSurface: calcPriceParam.volSurface,
              funding: calcPriceParam.discount,
              spotPrice: calcPriceParam.spotPrice == '0' ? '' : calcPriceParam.spotPrice,
              spotQuoteType: calcPriceParam.spotQuoteType
            }
          ],
          discount: calcPriceParam.discount,
          'customPricingParam': {}
        },
        underlyingMarkets: [
          {
            'underlyingID': form.data.instrumentId,
            'fixingPrices': [],
            'observerPrices': []
          }
        ]
      }
      props.calc(otcOption, props.index, flag)
    }
  })
}
const getCalcPriceParam = () => {
  let calcPriceParam = proxy.$refs.PricingParamRef.getCalcPricingParam()
  return calcPriceParam
}
const save2CalcLog = () => {
  getInstrumentJson().then((res) => {
    if (Boolean(res)) props.save2CalcLog(res, props.index)
  })

}
const getFormData = () => {
  return form
}

defineExpose({
  calc, getPricingCfg, getCalcPriceParam, getFormData,proxy
})
onMounted(() => {
  /*获取默认定价配置*/
  // getPricingCfg()
  /*获取预填表单*/
  form.initFlag = props.isReCalc
  if (props.formData != null) {
    form.initFlag = isNotVoid(props.calcPricingParam)
    let data = props.formData.data || props.formData
    form.data = Object.assign(form.data, data)
  }
  // 这里获取DOM的value是旧值
  nextTick(()=>{
    form.initFlag = false
  })
})


const onBlurEffectiveDate = () => {
  form.initFlag = false
  setSpotPrice()
}

/**
 * 获取标的价格
 * */
const setSpotPrice = () => {
  setCommonSpotPrice(proxy,form,props)
}
watch(()=>form,()=>{

  proxy.$attrs.cacheFormData()
},{deep:true})
</script>
<style>

</style>

